package com.whut.mall.service.impl;

import com.whut.mall.exception.ExceptionEnum;
import com.whut.mall.exception.ExceptionMall;
import com.whut.mall.model.dao.ProductMapper;
import com.whut.mall.model.dao.UserMapper;
import com.whut.mall.model.pojo.User;
import com.whut.mall.service.UserService;
import com.whut.mall.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;


/**
 * @author xh
 * @date 2022/3/16 10:52
 * UserService实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public void register(String userName, String password) throws ExceptionMall {
        //查询用户名是否重名，不允许用户名重名
        User result = userMapper.selectByName(userName);
        if (result != null){
            throw new ExceptionMall(ExceptionEnum.NAME_EXISTED);
        }

        //写到数据库
        User user = new User();
        user.setUsername(userName);
        //密码需要MD5加密
        try {
            user.setPassword(MD5Utils.getMD5Str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        //user.setPassword(password);
        int count = userMapper.insertSelective(user);
        if(count == 0){
            throw new ExceptionMall(ExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String userName, String password) throws ExceptionMall {
        String md5Password = null;
        try {
            md5Password = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        User user = userMapper.selectLogin(userName, md5Password);
        if(user == null){
            throw new ExceptionMall(ExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }

    @Override
    public void updateInformation(User user) throws ExceptionMall {
        //更新个性签名
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        if(updateCount > 1){
            throw new ExceptionMall(ExceptionEnum.UPDATE_FAILED);
        }
    }

    @Override
    public boolean checkAdminRole(User user){
        //1是普通用户 2是管理员
        return user.getRole().equals(2);
    }
}
